<template>
  <div>
    <!-- mian -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <div style="margin-top: 15px;">
        <el-row :gutter="10">
          <el-col :span="7">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              class="input-with-select"
              clearable
              @keyup.enter.native="getUserList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="Adduser">添加用户 </el-button>
            <el-dialog
              title="添加用户"
              :visible.sync="dialogFormVisible"
              width="500px"
            >
              <el-form :model="form" :rules="rules" ref="loginRef">
                <el-form-item
                  label="用户名"
                  :label-width="formLabelWidth"
                  prop="username"
                >
                  <el-input
                    autocomplete="off"
                    v-model="form.username"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="密码"
                  :label-width="formLabelWidth"
                  prop="password"
                  type="password"
                >
                  <el-input
                    autocomplete="off"
                    v-model="form.password"
                    type="password"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="邮箱"
                  :label-width="formLabelWidth"
                  prop="email"
                >
                  <el-input autocomplete="off" v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item
                  label="手机号"
                  :label-width="formLabelWidth"
                  prop="mobile"
                >
                  <el-input autocomplete="off" v-model="form.mobile"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="sure">确 定</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </div>
      <!-- 用户列表区 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index" label="#" width="80"> </el-table-column>
        <el-table-column prop="username" label="用户名" width="150">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="150">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="150">
        </el-table-column>
        <el-table-column prop="address" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#666"
              @change="useeStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改内容"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="usermodifyBut(scope.row)"
              >
              </el-button>
            </el-tooltip>
            <el-dialog
              title="修改内容"
              :visible.sync="usermodify"
              width="500px"
            >
              <el-form :model="modify" :rules="rules" ref="modify">
                <el-form-item
                  label="用户名"
                  :label-width="formLabelWidth"
                  prop="username"
                >
                  <el-input
                    autocomplete="off"
                    v-model="modify.username"
                    :disabled="true"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="邮箱"
                  :label-width="formLabelWidth"
                  prop="email"
                >
                  <el-input
                    autocomplete="off"
                    v-model="modify.email"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="手机号"
                  :label-width="formLabelWidth"
                  prop="mobile"
                >
                  <el-input
                    autocomplete="off"
                    v-model="modify.mobile"
                  ></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="usermodify = false">取 消</el-button>
                <el-button type="primary" @click="suremodify(modify)"
                  >确 定</el-button
                >
              </div>
            </el-dialog>
            &nbsp;
            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除内容"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="del(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 分配按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="distribution(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-dialog
              title="分配角色"
              :visible.sync="distributionB"
              width="30%"
            >
              <span>当前的用户：{{ distUsername }}</span>
              <br /><br />
              <span>当前的角色：{{ distRolename }}</span>
              <br />
              <br />
              <el-form :model="dist">
                <el-form-item label="活动名称" label-width="distributionB">
                  <el-select
                    v-model="dist.id"
                    placeholder="请选择"
                    @change="onchange"
                  >
                    <el-option
                      v-for="list in distList"
                      :key="list.id"
                      :label="list.roleName"
                      :value="list.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button @click="distributionB = false">取消</el-button>
                  <el-button type="primary" @click="ondist(dist)"
                    >确定</el-button
                  >
                </el-form-item>
              </el-form>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        small
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //获取用户列表参数
      queryInfo: {
        query: "",
        // 当前页码
        pagenum: 1,
        // 每页显示多少条
        pagesize: 4,
      },
      userlist: [],
      // 总数量
      total: null,
      dialogFormVisible: false,
      usermodify: false,
      // 添加用户数据信息
      form: {
        username: "111",
        password: "123456",
        email: "11@qq.com",
        mobile: "15000000000",
      },
      //添加用户信息表单 属性的宽度
      formLabelWidth: "80px",
      //校验规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            required: true,
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 修改用户数据信息
      modify: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        id: null,
      },
      //分配角色
      distid: "",
      distUsername: "",
      distRolename: "",
      distributionB: false,
      dist: {
        rid: "",
      },
      distList: [],
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //获取用户列表信息
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status != 200)
        return this.$message.error("获取用户列表失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    // 分页
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList(this.queryInfo.pagesize);
    },
    //跳转
    handleCurrentChange(num) {
      this.queryInfo.pagenum = num;
      this.getUserList();
    },
    //监听swirch开关变化
    async useeStateChange(suerInfo) {
      console.log(suerInfo);
      const { data } = await this.$http.put(
        `users/${suerInfo.id}/state/${suerInfo.mg_state}`
      );
      if (data.meta.status != 200) {
        suerInfo.mg_state = !suerInfo.mg_state;
        return this.$message.error("更新数据失败");
      }
      this.$message.success("更新用户状态成功");
    },
    //新增用户-点击取消
    cancel() {
      this.form.username = "";
      this.form.password = "";
      this.form.email = "";
      this.form.mobile = "";
      this.dialogFormVisible = false;
      this.$refs.loginRef.resetFields();
      console.log(this.$refs.loginRef);
    },
    //新增用户-点击添加用户
    Adduser() {
      this.dialogFormVisible = true;
      this.rules = this.rules;
    },
    //新增用户-确定增加用户
    sure() {
      this.$refs.loginRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return false;
        const { data: res } = await this.$http.post("users", this.form);
        console.log(res);
        if (res.meta.status != 201) return this.$message.error("添加用户失败");

        this.$message.success("用户添加成功");
        this.dialogFormVisible = false;
        this.getUserList();
      });
    },
    //点击修改用户信息--点击按钮打开弹窗
    usermodifyBut(userInfo) {
      console.log(userInfo);
      this.usermodify = true;
      this.modify.username = userInfo.username;
      this.modify.mobile = userInfo.mobile;
      this.modify.email = userInfo.email;
      this.modify.id = userInfo.id;
    },
    //修改用户信息--提交数据
    suremodify(userInfo) {
      console.log(userInfo);
      this.$refs.modify.validate(async (valid) => {
        if (!valid) return false;
        const { data } = await this.$http.put(`users/${userInfo.id}`, {
          id: userInfo.id,
          mobile: userInfo.mobile,
          email: userInfo.email,
        });
        console.log(data);
        if (data.meta.status != 200) return this.$message.error("修改数据失败");
        this.$message.success("修改数据成功");
        this.getUserList();
        this.usermodify = false;
      });
    },
    //删除用户数据
    async del(val) {
      const { data } = await this.$http.delete(`users/${val.id}`);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // this.$http.delete(`users/${val.id}`).then((res) => {
          //   console.log(res);
          if (data.meta.status != 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");

          this.getUserList();
          // });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //点击分配角色 按钮
    async distribution(val) {
      console.log(val);
      this.distRolename = val.role_name;
      this.distUsername = val.username;
      this.distid = val.id;
      this.distributionB = true;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200)
        return this.$message.error("获取用户权限失败");
      this.distList = res.data;
    },
    //获取角色 id
    onchange(val) {
      this.rid = val;
    },
    //分配角色 确定按钮
    async ondist(val) {
      console.log(val);
      console.log(this.distid);
      const { data } = await this.$http.put(`users/${this.distid}/role`, {
        id: this.distid,
        rid: val.id,
      });
      if (data.meta.status != 200)
        return this.$message.error("修改角色权限失败");
      this.$message.success("修改角色权限成功");
      this.distributionB = false;
      this.getUserList();
    },
  },
};
</script>

<style scoped>
.el-table {
  font-size: 12px;
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
  text-align: center;
}
</style>
